package com.xiaoq.matrix.toutiao.endpoint;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import com.xiaoq.apis.user.MerchantMgrInfo4Vo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.UnicodeUtil;
import com.xiaoq.matrix.entity.ContentMediaAccountEntity;
import com.xiaoq.matrix.service.IContentMediaAccountService;
import com.xiaoq.matrix.service.IContentMediaService;
import com.xiaoq.matrix.service.IMerchantMgrService;
import com.xiaoq.matrix.toutiao.util.TouTiaoException;
import com.xiaoq.matrix.toutiao.util.TouTiaoOauth;
import com.xiaoq.matrix.toutiao.util.TouTiaoTokenStatus;
import com.xiaoq.matrix.toutiao.util.TouTiaoAccessToken;
import com.xiaoq.matrix.toutiao.util.TouTiaoArticle;
import com.xiaoq.matrix.toutiao.util.TouTiaoArticleStatus;
import com.xiaoq.matrix.toutiao.vo.TouTiaoVo;


@RestController
@RequestMapping("/api/v1/toutiao")
public class TouTiaoEndpoint {
	
	@Autowired
	private IContentMediaService contetnMediaSrv;
	
	@Autowired
	private IMerchantMgrService merMgerSrv;
	
	@Autowired
	private IContentMediaAccountService contentMediaAccountSrv;
	
	private Logger logger= LoggerFactory.getLogger(TouTiaoEndpoint.class);
	
	@ApiOperation(value = "点击认证头条", notes = "根据超链接认证头条")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "认证头条") })
	@GetMapping(value = "/{userId}/toutiao", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> toutiaoOauth(@PathVariable(value="userId",required=false)@ApiParam(value="userId",required=false)String userId){
		
		TouTiaoOauth oauth =new TouTiaoOauth();
		try {
			String openUrl = oauth.authorize("code",userId);
			return GenericDataResponse.okWithData(openUrl);
		} catch (TouTiaoException e) {
			String errrorMsg = "获取code失败";
			logger.error(errrorMsg, e);
			return GenericResponse.ng(errrorMsg);
		}
		
	}
	
	@ApiOperation(value = "获取今日头条返回的code", notes = "获取今日头条返回的code")
	@GetMapping(value = "/code", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public void getCode(
			@RequestParam(value = "code", required = false) @ApiParam(value = "code", required = false) String code,
			@RequestParam(value = "state", required = true) @ApiParam(value = "state", required = true) String state,
			@RequestParam(value = "error_code", required = false) @ApiParam(value = "error_code", required = false) String error_code,
			HttpServletRequest request,HttpServletResponse response) {
		String out = "http://p0sd9v5tn.bkt.clouddn.com/success.html";
		String fail = "http://p0sd9v5tn.bkt.clouddn.com/fail.html";
		if (error_code == null) {

			TouTiaoOauth oauth = new TouTiaoOauth();

			TouTiaoTokenStatus tokenStatus = oauth.getAccessTokenByCode(code);
			if (tokenStatus != null) {
				ContentMediaAccountEntity contentMediaAccount = getMediaAccount(tokenStatus);
				if(contentMediaAccount!=null){
					logger.info(contentMediaAccount.toString());
					MerchantMgrInfo4Vo merchantMgr = merMgerSrv.findMerMger(state);
					if(merchantMgr!=null){
						String merChantId = merchantMgr.getMerchantId();
						if(StringUtils.isNotEmpty(merChantId)){
							contentMediaAccount.setMerchantId(merChantId);
							contentMediaAccountSrv.saveContentMediaAccount(contentMediaAccount);
							try {
								response.sendRedirect(out);
							} catch (IOException e) {
								logger.error(e.getMessage(),e);
							}
						}else{
							logger.error("请认证商店后进行此操作");
							try {
								response.sendRedirect(fail);
							} catch (IOException e) {
								logger.error(e.getMessage(),e);
							}
						}
						
					}else{
						logger.error("merchantMgr空指针异常！");
						try {
							response.sendRedirect(fail);
						} catch (IOException e) {
							logger.error(e.getMessage(),e);
						}
					}
					
					
					
				}else{
					logger.error("ContentMediaAccountEntity 返回结果为空报空指针异常！");
					try {
						response.sendRedirect(fail);
					} catch (IOException e) {
						logger.error(e.getMessage(),e);
					}
				}
				
			} else {

				logger.error("tokenStatus获取空指针异常");
				try {
					response.sendRedirect(fail);
				} catch (IOException e) {
					logger.error(e.getMessage(),e);
				}
			}

		} else {
			try {
				response.sendRedirect(fail);
			} catch (IOException e) {
				logger.error(e.getMessage(),e);
			}
		}

	}
	@ApiOperation(value = "发头条", notes = "发头条")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "发头条") })
	@PostMapping(value = "/toutiaocon", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> sendArticle(@RequestBody TouTiaoVo touTiaoVo){
		String mediaId = contetnMediaSrv.findContentMedia("今日头条").getId();
		String merchantId=merMgerSrv.findMerMger(touTiaoVo.getUserId()).getMerchantId();
		ContentMediaAccountEntity contentMediaAccount = contentMediaAccountSrv.findContentMediaAccount(merchantId, mediaId);
		String access_token = contentMediaAccount.getToken();
		
		Map<String, String> touTiaoParam = new HashMap<>();
		touTiaoParam.put("title", touTiaoVo.getTitle());
		touTiaoParam.put("content", touTiaoVo.getContent());
		touTiaoParam.put("abstract", touTiaoVo.getAbStract());
		touTiaoParam.put("save", touTiaoVo.getSave());
//		touTiaoParam.put("article_tag", touTiaoVo.getArticle_tag());
		touTiaoParam.put("access_token", access_token);
		
		TouTiaoArticleStatus ttArticleStatus = TouTiaoArticle.updateStatus(touTiaoParam);
		if(ttArticleStatus!=null){
			String msg = ttArticleStatus.getMessage();
			if(msg.equals("error")){
				logger.debug("与头条访问api的连接出错！");
				return GenericResponse.ng(UnicodeUtil.ascii2native(ttArticleStatus.getData()));
			}else{
				return GenericResponse.ok();
			}
		}else{
			logger.error("ttArticleStatus空指针异常！");
			return GenericResponse.ng("发送头条信息失败！");
		}
		
		
		
	}
	
	protected ContentMediaAccountEntity getMediaAccount(TouTiaoTokenStatus tokenStatus) {
		ContentMediaAccountEntity contentMediaAccount = new ContentMediaAccountEntity();
		TouTiaoAccessToken touTiaoAccessToken = tokenStatus.getData();
		if (touTiaoAccessToken != null) {
			String accessToken = touTiaoAccessToken.getAccessToken();
			Long uid = touTiaoAccessToken.getUid();
			if (accessToken != null) {
				contentMediaAccount.setToken(accessToken);
				contentMediaAccount.setRefreshToken(""); // 头条直接就不返回refreshToken这个参数了
				Long currentTime = System.currentTimeMillis();
				contentMediaAccount.setTokenTime(currentTime);
				if (uid != 0) {
					contentMediaAccount.setAccount(uid + "");
				} else {
					contentMediaAccount.setAccount("");
				}
				contentMediaAccount.setTokenDuratio(Long.parseLong(tokenStatus.getData().getExpiresIn()));
				contentMediaAccount.setMediaId(contetnMediaSrv.findContentMedia("今日头条").getId());
				return contentMediaAccount;
			} else {
				logger.debug("accessToken 获取为空！");
				return null;
			}

		}
		logger.debug("touTiaoAccessToken 获取为空！");
		return null;

	}

}
